#include "form2.h"
#include "ui_form2.h"
#include <QDebug>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

Form2::Form2(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form2),
    fd(-1), // 初始化文件描述符
    dev_status(0) // 初始化蜂鸣器状态
{
    ui->setupUi(this);
    // 连接按钮的 clicked 信号到槽函数
    connect(ui->pushButton, &QPushButton::clicked, this, &Form2::toggleBuzzer);

    // 打开蜂鸣器设备文件
    fd = open("/dev/drv_beep0", O_RDWR);
    if(fd < 0)
    {
        qDebug() << "Failed to open /dev/drv_beep0";
    }
}

Form2::~Form2()
{
    if (fd != -1) {
        ::close(fd); // 关闭设备文件
    }
    delete ui;
}

void Form2::toggleBuzzer()
{
    if (fd < 0) {
        qDebug() << "Device file is not open";
        return;
    }

    // 写入设备文件以控制蜂鸣器
    if (write(fd, &dev_status, sizeof(int)) < 0) {
        qDebug() << "Failed to write to device file";
        return;
    }

    // 切换蜂鸣器状态
    dev_status = !dev_status;
    qDebug() << "Buzzer status:" << (dev_status ? "ON" : "OFF");
}
